import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button,  Dropdown, Menu, Card,Switch,Drawer,Divider,message,Popconfirm} from 'antd';
import { formatMessage } from 'umi-plugin-react/locale';
import React, { useState, useRef } from 'react';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import DataForm from './components/DataForm';
import { TableListItem } from './data';
import { queryRule, updateRule, queryEmojiItemRule, removeEmojiItemRule,addEmojiItemRule, updateEmojiItemRule ,removeRule} from './service';
import { bdExec } from '@/helpers/RequestHelper';
import EmojiForm from './components/EmojiForm';
import DictoryForm from './components/DictoryForm';
import styles from './style.less';

import * as RequestHelper from '@/helpers/RequestHelper';
import PreviewForm from '@/components/PreviewForm';
import { FormValueType } from '@/pages/crm/depart/components/UpdateForm';
import * as TsxHelper from '@/helpers/TsxHelper';
interface TableListProps extends FormComponentProps {}


const TableList: React.FC<TableListProps> = () => {
    // 初始化变量区
    // 维护API状态数据
    const [apiState, setApiState] = useState<any>({common:{}});
    // 是否更新 关键变量
    const [isUpdate, setIsUpdate] = useState<boolean>(false);
    // 表单可见 关键变量
    const [dataModalVisible, handleDataModalVisible] = useState<boolean>(false);
    // 图片预览
    const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
    const [previewImg, setPreviewImg] = useState('');
    // 表单数据
    const [dataFormValues, setDataFormValues] = useState({});
    // 选中的记录
    const [rowKeys, setRowKeys] = useState<string[]|number[]>([]);

    const [parentId, setParentId] = useState<any>('');
    const [drawerVisible,setDrawerVisible] = useState<boolean>(false);
    const [emojiValue, setEmojiValue] = useState<any>({});
    const [itemIsUpdate, setItemIsUpdate] = useState<boolean>(false);
    const [dictoryIsUpdate, setDictoryIsUpdate] = useState<boolean>(false);
    const [dictoryModalVisible, handleDictoryModalVisible] = useState<boolean>(false);

    const actionRef = useRef<ActionType>();
    const itemActionRef = useRef<ActionType>();

    // 列定义
    const columns: ProColumns<any>[] = [
        {
            title: '显示顺序',
            dataIndex: 'rank_num',
            width: 150,
        },
        {
          title: '启用状态',
          dataIndex: 'is_enable',
          render: (value, record) => (
            <Switch checked={record.is_enable} onChange={async () => {
              let s = await handleUpdateItem({id: record.id, is_enable: (!record.is_enable).toString()});
              s && actionRef.current?.reload();
            }} />
          )
        },
        {
          title: '表情小组名',
          dataIndex: 'name',
          hideInSearch: true,
        },
        {
          title: '表情标识图',
          dataIndex: 'image_file_url',
          hideInSearch: true,
          render: (value, record) => (
              <img src={record.image_file_url} width='80px' onClick={() => {
                  setPreviewImg(record.image_file_url)
                  handlePreviewModalVisible(true)
              }} />
          )
      },
        {
            title: '表情数量',
            dataIndex: 'count',
            hideInSearch: true,
        },
        // {
        //     title: '表情标识图',
        //     dataIndex: 'count',
        //     hideInSearch: true,
        // },
        {
            title: formatMessage({ id: 'app.base.option' }),
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => (
                <>
                <a
                    onClick={() => {
                      setParentId(record.id);
                      setDrawerVisible(true);
                      setEmojiValue(record);
                    }}
                >
                    管理
                </a>
                <Divider type="vertical"></Divider>
                <a
                    onClick={() => {
                        handleDictoryModalVisible(true);
                        setIsUpdate(true)
                        setDataFormValues(record)
                    }}
                >
                    编辑
                </a>
                <Divider type="vertical"></Divider>
                <Popconfirm
                  title="确认删除吗？"
                  onConfirm={()=>{deleteData(record.key)}}
                  okText="确认"
                  cancelText="取消"
                >
                  <a> {formatMessage({ id: 'app.base.delete' })}</a>
                </Popconfirm>
                {/* <a
                    onClick={async e => {
                        TsxHelper.showDeleteConfirm(
                            'danger',
                            handleRemove,
                            record.id,
                            () => {
                                if (actionRef.current) {
                                    actionRef.current.reload();
                                }
                            }
                        )
                    }}
                >
                    {formatMessage({ id: 'app.base.delete' })}
                </a> */}
                </>
            ),
        },
    ];

    const itemColumns: ProColumns<any>[] = [
        {
            title: '顺序',
            dataIndex: 'rank_num',
            hideInSearch: true,
        },
        {
          title: '是否启用',
          dataIndex: 'is_enable',
          hideInSearch: true,
          render: (value, record) => (
            <Switch checked={record.is_enable} onChange={async () => {
              let s = await handleUpdateItem({id: record.id,  is_enable: (!record.is_enable).toString()});
              s && itemActionRef.current?.reload();
            }} />
          )
        },
        
        {
          title: '表情图片',
          dataIndex: 'image_file_url',
          hideInSearch: true,
          render: (value, record) => (
            <img src={record.image_file_url} width='130px' onClick={() => {
                setPreviewImg(record.image_file_url)
                handlePreviewModalVisible(true )
            }} />
          )
        },
        {
            title: '表情符号',
            dataIndex: 'code',
            hideInSearch: true,
        },
        {
            title: formatMessage({ id: 'app.base.option' }),
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => (
                <>
                <a
                    onClick={() => {
                      handleDataModalVisible(true);
                      setEmojiValue(record);
                      setItemIsUpdate(true);
                    }}
                >
                    编辑
                </a>
                <Divider type="vertical"></Divider>
                {/* <Popconfirm
                  title="确认删除吗？"
                  onConfirm={()=>{deleteData(record.key)}}
                  okText="确认"
                  cancelText="取消"
                >
                  <a> {formatMessage({ id: 'app.base.delete' })}</a>
                </Popconfirm> */}
                <a
                    onClick={async e => {
                        TsxHelper.showDeleteConfirm(
                            'danger',
                            handleEmojiItemRemove,
                            record.id,
                            () => {
                                if (itemActionRef.current) {
                                    itemActionRef.current.reload();
                                }
                            }
                        )
                    }}
                >
                    {formatMessage({ id: 'app.base.delete' })}
                </a>
                </>
            ),
        },
    ];

    // 请求接口数据, 设置组件状态
    const getTableData = (params:any) => {
        return queryRule(params).then((res:any) => {
            setApiState(res.data)
            return res.data.listData
        })
    }

    const getEmojiTableData = (params:any) => {
        return queryEmojiItemRule(params).then((res:any) => {
          
            setApiState(res.data)
            return res.data.listData
          
            
        })
      }

    // 表单提交
    const handleItemSubmitDataForm = (value:any) => {
        return new Promise((resolve, reject) => {
            let s = itemIsUpdate ? handleUpdate(value) : handleAdd(value);
            resolve(s);
        }).then( status => {
            console.log("handleSubmitDataForm status is ", status)
            if(status){
                handleDataModalVisible(false)
                // setIsUpdate(false)
                // setDataFormValues({})
                if (itemActionRef.current) {
                  itemActionRef.current.reload();
                }
            }
            // 返回执行结果:boolean, 子组件接收此值来重置数据
            return status;
        })
    }

    // 表单提交
    const handleSubmitDataForm = (value:any) => {
        return new Promise((resolve, reject) => {
            let s = isUpdate ? handleUpdate(value) : handleAdd(value);
            resolve(s);
        }).then( status => {
            console.log("handleSubmitDataForm status is ", status)
            if(status){
                handleDataModalVisible(false)
                setIsUpdate(false)
                setDataFormValues({})
                if (actionRef.current) {
                    actionRef.current.reload();
                }
                handleDictoryModalVisible(false)
            }
            // 返回执行结果:boolean, 子组件接收此值来重置数据
            return status;
        })
    }

     //删除接口
     const deleteData = (id:any) => {
      var params = {
          ids: id,
      }
      removeRule(params).then(res=>{
          if(res.code == 0){
              message.success('删除成功！')
              if (actionRef.current) {
                actionRef.current.reload();
              }
          }else{
              message.error(res.message)
          }
          
      })
  }

    const content = (
        <div className={styles.pageHeaderContent}>
            <p>
            启用表情后将在编辑器的输入框有表情包列表，但是数据库原生支持 Emoji 表情符，所以不启用的情况下，用户也可以通过表情键盘输入 Emoji 表情。
            </p>
        </div>
      );

    return (
        <PageHeaderWrapper
            content={content}
        >
            <ProTable<any>
            headerTitle=""
            actionRef={actionRef}
            rowKey="key"
            search={false}
            toolBarRender={(action, { selectedRows }) => [
            
              // @ts-ignore
              <Button icon={<PlusOutlined />} type="primary" onClick={() => { setIsUpdate(false); setDataFormValues({});handleDictoryModalVisible(true);}}>
                {formatMessage({ id: 'app.base.create' })}
              </Button>
          ]}
            request={params => getEmojiTableData(params)}
            columns={columns}
            rowSelection={false}
            />
            {dataModalVisible == true &&
              <EmojiForm
                dataModalVisible={dataModalVisible}
                isUpdate={itemIsUpdate}
                parentId={parentId}
                dataFormValues={emojiValue}
                common={apiState.common || {}}
                onSubmit={ async formValue => handleItemSubmitDataForm(formValue) }
                onCancel={() => handleDataModalVisible(false)}
              />
            }
    {dictoryModalVisible == true &&
      <DictoryForm
        dataModalVisible={dictoryModalVisible}
        isUpdate={isUpdate}
        dataFormValues={dataFormValues}
        common={apiState.common || {}}
        onSubmit={ async formValue => handleSubmitDataForm(formValue) }
        onCancel={() => handleDictoryModalVisible(false)}
      />
    }
    <Drawer
          // title={`字典: ${parentDictName}`}
          placement="right"
          width="39%"
          closable={false}
          onClose={() => {
            setDrawerVisible(false)
            // setItemModalVisible(false)
          }}
          visible={drawerVisible}
          className={styles.dbDrawer}
        >
          <ProTable<any>
            headerTitle={`表情管理`}
            actionRef={itemActionRef}
            rowKey="key"
            search={false}
            // pagination={false}
            toolBarRender={(action, { selectedRows }) => [
              <Button icon={'plus'} type="primary" 
                onClick={() => {
                  handleDataModalVisible(true);
                  setItemIsUpdate(false);
                }}
              >
                新建
              </Button>
            ]}
            request={(params) => getEmojiTableData(params)}
            params={{
              parent_id: parentId
            }}
            columns={itemColumns}
          />
        </Drawer>
              {
                  previewModelVisible && (
                      <PreviewForm
                          previewModelVisible={previewModelVisible}
                          onVisibleModel={handlePreviewModalVisible}
                          previewImg={previewImg}
                      />
                  )
              }
        </PageHeaderWrapper>
    );
};

/**
* 添加节点
* @param fields
*/
const handleAdd = async (fields: any) => {
    return RequestHelper.bdExec({
        fn: addEmojiItemRule,
        args: fields,
        successMsg: formatMessage({ id: 'app.base.store-success' }),
        failMsg: formatMessage({ id: 'app.base.api-exception' }),
    });
};

/**
* 更新节点
* @param fields
*/
const handleUpdate = async (fields: FormValueType) => {
    return RequestHelper.bdExec({
        fn: updateEmojiItemRule,
        args: fields,
        successMsg: formatMessage({ id: 'app.base.update-success' }),
        failMsg:  formatMessage({ id: 'app.base.api-exception' }),
    });
};

const handleUpdateItem = async (fields: any) => {
    return bdExec({fn: updateEmojiItemRule, args: fields, successMsg: '更新成功',failMsg: '更新失败请重试！'});
  };
  
// @ts-ignore
/**
 *  删除节点
 */
const handleEmojiItemRemove = async (selectedRows: TableListItem[]) => {
    if (!selectedRows) return true;
    const ids:any = selectedRows;
    return RequestHelper.bdExec({
        fn: removeEmojiItemRule,
        args: {ids},
        successMsg: formatMessage({ id: 'app.base.destroy-success' }),
        failMsg:  formatMessage({ id: 'app.base.api-exception' }),
        hasLoading: false
    });
};
const handleRemove = async (selectedRows: TableListItem[]) => {
  if (!selectedRows) return true;
  const ids:any = selectedRows;
  return RequestHelper.bdExec({
      fn: removeEmojiItemRule,
      args: {ids},
      successMsg: formatMessage({ id: 'app.base.destroy-success' }),
      failMsg:  formatMessage({ id: 'app.base.api-exception' }),
      hasLoading: false
  });
};



export default Form.create<TableListProps>()(TableList);
